Page({
  data: {
    theme: 'light',
    schema:[
      {
        label:'key',
        prop:'key',
        type:'text'
      },{
        label:'data',
        prop:'data',
        type:'text'
      }
    ],
    title:'数据缓存',
    formData:{
      key:'',
      data:''
    },
    result:''
  },

  formDataChange(e) {
    this.setData({
      formData:e.detail.formData
    })
  },

  getStorage() {
    const {key} = this.data.formData
    if(key) {
      wx.getStorage({
        key,
        complete:(e)=>{
          this.setData({
            result:e
          })
        }
      })
    }else {
      wx.getStorageInfo({
        complete:(e)=>{
          this.setData({
            result:e
          })
        }
      })
    }
  },
  getStorage1() {
    const {key, data} = this.data
    let storageData

    if (key.length === 0) {
      this.setData({
        key,
        data,
      })
      wx.showModal({
        title: '读取数据失败',
        content: 'key 不能为空'
      })
    } else {
      storageData = wx.getStorageSync(key)
      console.log(storageData)
      if (storageData === '') {
        this.setData({
          key,
          data: storageData
        })
        wx.showModal({
          title: '读取数据失败',
          content: '找不到 key 对应的数据'
        })
      } else {
        this.setData({
          key,
          data: storageData
        })
        wx.showModal({
          title: '读取数据成功',
          content: storageData,
        })
      }
    }
  },

  setStorage() {
    const {key, data} = this.data.formData
    if (key.length === 0) {
      wx.showModal({
        title: '保存数据失败',
        content: 'key 不能为空'
      })
    } else {
      wx.setStorage({
        key,
        data,
        complete:(e)=>{
          this.setData({
            result:e
          })
        }
      })
      wx.showToast({
        title: '存储数据成功',
      })
      this.setData({
        'formData.key':'',
        'formData.data':''
      })
    }
  },

  clearStorage() {
    wx.clearStorage({
      complete:(e)=>{
        this.setData({
          result:e
        })
      }
    })
  },
  onLoad() {
    this.setData({
      theme: wx.getSystemInfoSync().theme || 'light'
    })

    if (wx.onThemeChange) {
      wx.onThemeChange(({theme}) => {
        this.setData({theme})
      })
    }
  }
})
